import uuid
from django.db import models
from django.utils import timezone

from apps.AssetsManagement.models import Asset
from apps.CanvasesManagement.models import Canvas


class TemplateCategory(models.Model):
    """模板分类表"""
    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False,
                          verbose_name="分类唯一标识", max_length=255)
    name = models.CharField("分类名称", max_length=100, help_text="如口红、面霜等")
    description = models.TextField("分类描述", blank=True, null=True)
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,
                               related_name='children', verbose_name="父分类ID")
    icon_url = models.CharField("分类图标URL", max_length=200)
    position = models.IntegerField("展示顺序", null=True, blank=True, db_index=True)
    created_at = models.DateTimeField("创建时间", default=timezone.now, db_index=True)
    updated_at = models.DateTimeField("更新时间", auto_now=True)

    class Meta:
        db_table = 'template_categories'
        verbose_name = '模板分类表'
        verbose_name_plural = '模板分类表'
        ordering = ['position']

    def save(self, *args, **kwargs):
        # 如果 position 为空，则自动设定为当前项目中最大的 position + 1
        if self.position is None:
            last_category = TemplateCategory.objects.filter(parent=self.parent).order_by('-position').first()
            self.position = last_category.position + 1 if last_category and last_category.position is not None else 1
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.name} ({self.id})"


def default_canvas_size():
    return {'width': 1920, 'height': 1080}

def default_background():
    return {
        "type": "color",
        "value": "#ffffff",
        "position": {
            "x": 0,
            "y": 0
        },
        "size": "cover",
        "opacity": 1
    }


class Template(models.Model):
    """模板表"""
    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False,
                          verbose_name="模板唯一标识", max_length=255)
    category = models.ForeignKey(TemplateCategory, on_delete=models.CASCADE,
                                 related_name='templates', verbose_name="所属分类ID")
    name = models.CharField("模板名称", max_length=100)
    description = models.TextField("模板描述", blank=True, null=True)
    thumbnail_url = models.CharField("缩略图URL", max_length=200)
    canvas_size = models.JSONField("画布默认尺寸", default=default_canvas_size,
                                   help_text="格式：{'width': value, 'height': value}")
    background = models.JSONField("背景设置", default=default_background, help_text="背景相关配置")
    preview_url = models.CharField("预览图URL", max_length=200, blank=True, null=True)
    internal_notes = models.TextField("内部备注", blank=True, null=True)
    created_at = models.DateTimeField("创建时间", default=timezone.now, db_index=True)
    updated_at = models.DateTimeField("更新时间", auto_now=True)

    class Meta:
        db_table = 'templates'
        verbose_name = '模板表'
        verbose_name_plural = '模板表'
        indexes = [
            models.Index(fields=['-created_at'], name='template_created_desc_idx')
        ]

    def __str__(self):
        return f"{self.name} ({self.category.name})"


class TemplateElement(models.Model):
    """模板元素表"""
    objects = models.Manager()

    ELEMENT_TYPE_CHOICES = [
        ('mask', 'Mask'),
        ('text', 'Text'),
        ('group', 'Group'),
    ]

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False,
                          verbose_name="元素唯一标识", max_length=255)
    origin_element_id = models.CharField(verbose_name="原始导出元素ID", max_length=255, null=True, blank=True)
    template = models.ForeignKey(Template, on_delete=models.CASCADE,
                                 related_name='elements', verbose_name="关联模板ID")
    type = models.CharField(max_length=10, choices=ELEMENT_TYPE_CHOICES, verbose_name="元素类型")
    name = models.CharField(max_length=100, verbose_name="元素名称", null=True, blank=True)
    content = models.JSONField("元素内容和配置（mask和text配置）", default=dict)
    position = models.JSONField("位置信息", default=dict,
                                help_text="格式：{'x': value, 'y': value}")
    size = models.JSONField(default=dict, verbose_name="尺寸信息", help_text="格式：{'width': value, 'height': value}")
    rotation = models.FloatField(default=0.0, verbose_name="旋转角度")
    opacity = models.FloatField(default=1.0, verbose_name="透明度 (0-1)")
    visible = models.BooleanField(default=True, verbose_name="是否可见")
    locked = models.BooleanField(default=False, verbose_name="是否锁定")
    z_index = models.IntegerField("层级顺序", default=0)
    frame_style = models.JSONField(default=dict, verbose_name="边框样式",
                                   help_text="格式：{border: '5px solid', borderColor: '#4a90e2', borderRadius: '15%'}")
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, related_name='template_elements',
                              verbose_name="关联资源ID", null=True, blank=True)
    group_parent_id = models.CharField(max_length=255, null=True, blank=True, verbose_name="父group_id")

    class Meta:
        db_table = 'template_elements'
        verbose_name = '模板元素表'
        verbose_name_plural = '模板元素表'
        ordering = ['z_index']

    def get_default_content(self):
        if self.type == 'text':
            return {
                "text_content": "默认文本",
                "font_family": "Arial",
                "font_size": "12.0",
                "font_weight": "normal",
                "font_style": "normal",
                "text_align": "left",
                "line_height": "1.2",
                "letter_spacing": "0.0",
                "text_color": "#000000",
                "text_effects": {},
                "text_transform": {},
                "writing_mode": "horizontal"
            }
        elif self.type == 'mask':
            return {
                "mask_type": "image",
                "mask_content": {}
            }
        return {}

    def save(self, *args, **kwargs):
        # 如果 content 为空，按 type 设置默认内容
        if not self.content:
            self.content = self.get_default_content()
        super().save(*args, **kwargs)


class TemplateLayerGroup(models.Model):
    """模版图层组表"""
    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255)
    template = models.ForeignKey(Template, on_delete=models.CASCADE, related_name='template_layer_groups',
                                 verbose_name="关联模板ID")
    name = models.CharField(max_length=100, verbose_name="图层组名称")
    visible = models.BooleanField(default=True, verbose_name="是否可见")
    locked = models.BooleanField(default=False, verbose_name="是否锁定")
    z_index = models.IntegerField(default=0, verbose_name="组图层")
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children',
                               verbose_name="父图层组")

    class Meta:
        db_table = 'template_layer_groups'
        verbose_name = '模板图层组表'
        ordering = ['z_index']
        indexes = [models.Index(fields=['z_index'], name='z_index_template_group_idx')]

    def __str__(self):
        return f"{self.name} ({self.template.name})"


class TemplateLayerGroupElement(models.Model):
    """图层组与元素关联表"""
    objects = models.Manager()

    group = models.ForeignKey(TemplateLayerGroup, on_delete=models.CASCADE, related_name='element_group_mapping',
                              verbose_name="图层组ID")
    element = models.ForeignKey(TemplateElement, on_delete=models.CASCADE, related_name='element_group_mapping',
                                verbose_name="元素ID")

    class Meta:
        db_table = 'template_element_group_mapping'
        verbose_name = '模板图层组元素关联表'
        unique_together = ('group', 'element')


class TemplateTag(models.Model):
    """模板标签表"""
    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False,
                          verbose_name="标签唯一标识", max_length=255)
    name = models.CharField("标签名称", max_length=50, unique=True)

    class Meta:
        db_table = 'template_tags'
        verbose_name = '模板标签表'
        verbose_name_plural = '模板标签表'

    def __str__(self):
        return self.name


class TemplateTagMapping(models.Model):
    """模板-标签关联表"""
    objects = models.Manager()

    template = models.ForeignKey(Template, on_delete=models.CASCADE, verbose_name="模板ID")
    tag = models.ForeignKey(TemplateTag, on_delete=models.CASCADE, verbose_name="标签ID")

    class Meta:
        db_table = 'template_tag_mappings'
        verbose_name = '模板-标签关联表'
        verbose_name_plural = '模板-标签关联表'
        unique_together = ('template', 'tag')


class TemplateFavorite(models.Model):
    """模板收藏表"""
    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False,
                          verbose_name="收藏记录唯一标识", max_length=255)
    template = models.ForeignKey(Template, on_delete=models.CASCADE, verbose_name="模板ID")
    notes = models.TextField("收藏备注", blank=True, null=True)
    created_at = models.DateTimeField("收藏时间", default=timezone.now, db_index=True)

    class Meta:
        db_table = 'template_favorites'
        verbose_name = '模板收藏表'
        verbose_name_plural = '模板收藏表'
        ordering = ['-created_at']
